package de.uni.muenster.idw2.threads;

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import de.uni.muenster.idw2.data.BBBuilding;
import de.uni.muenster.idw2.data.DrawableObject;
import de.uni.muenster.idw2.interfaces.AdapterLoaderInterface;

public class LastBuildingImageLoaderThread extends AsyncTask<Void, DrawableObject, Void> implements AdapterLoaderInterface{
	
	private ArrayList<BBBuilding> bbBuildings;
	private ArrayList<ImageView> imageViews;
	private ArrayList<Drawable> drawables = new ArrayList<Drawable>(); 
	private final Activity act;
	private ProgressBar progressBar;

	public LastBuildingImageLoaderThread(Activity act, ArrayList<BBBuilding> bbBuildings, ArrayList<ImageView> imageViews, ProgressBar progressBar){
		this.act = act;
		this.bbBuildings = bbBuildings;
		this.imageViews = imageViews;
		this.progressBar = progressBar;
		for (BBBuilding b : bbBuildings) {
			drawables.add(null);
		}
		
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		progressBar.setVisibility(View.VISIBLE);
	}

	@Override
	protected Void doInBackground(Void... params) {
		
		ExecutorService executorService = Executors.newFixedThreadPool(6);
		for (int i = 0; i < bbBuildings.size(); i++) {
			Runnable worker = new SilngelImgThread(this, bbBuildings.get(i).getPathIMG(), i);
			executorService.execute(worker);
		}
		
		executorService.shutdown();
		
		while (!executorService.isTerminated()) {
			
		}
		
		return null;
	}
	
	@Override
	protected void onProgressUpdate(DrawableObject... values) {
		
		DrawableObject drawableObject = values[0];
		imageViews.get(drawableObject.getI()).setImageDrawable(drawables.get(drawableObject.getI()));
	}
	
	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		progressBar.setVisibility(View.GONE);
	}
	
	public synchronized void addImage(Drawable drawable,int i){
		drawables.add(i, drawable);
		DrawableObject drawableObject = new DrawableObject(i, drawable);
		publishProgress(drawableObject);
	}

}
